package thread;
//死锁 以两个线程为例当两个线程各自持有一个锁的过程中等待对方先释放锁就会形成一种僵持状态
//导致程序卡主无法在继续后面的执行，这个现象称为死锁
public class DeadLockDemo {
    private static Object chopsticks=new Object();
    private static Object spoon=new Object();
    public static void main(String[] args) {
        Thread np=new Thread(){
            public void run(){
                    try {  System.out.println("北方人:开始吃饭");
                        System.out.println("北方人去拿筷子...");
                        synchronized (chopsticks) {
                            System.out.println("北方人拿起了筷子，开始吃饭...");
                            Thread.sleep(5000);
                            System.out.println("北方人吃完了饭，去拿勺...");
                            synchronized (spoon){
                                System.out.println("北方人拿起了勺子，开始喝汤...");
                                Thread.sleep(5000);
                            }
                            System.out.println("北方人喝完了汤,北方人放下了勺子");
                        }
                        System.out.println("北方人放下了筷子，吃饭完毕。");
                } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };

        Thread sp=new Thread(){
            public void run(){
                try {
                    System.out.println("南方人开始吃饭");
                    System.out.println("南方人拿起勺子");
                    synchronized (spoon){
                        System.out.println("南方人拿起了勺子开始喝汤");
                        Thread.sleep(5000);
                        System.out.println("南方人喝完汤去拿筷子");
                        synchronized (chopsticks)
                        {
                            System.out.println("南方人拿起了筷子");
                            Thread.sleep(5000);
                        }
                        System.out.println("南方人放下了筷子吃饭完毕");
                    }
                    System.out.println("南方人放下来勺子吃饭完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        np.start();
        sp.start();
    }
}
